package com.imooc.concurrent.memoryVisibility;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 为保证原子性，使用AtomicInterger
 */
public class VolatileDemo4 {

	private AtomicInteger ai = new AtomicInteger(0);

	public int getNumber(){
		return ai.get();
	}

	public void increase(){
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//将number++三步合并为一步执行
		ai.getAndIncrement();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final VolatileDemo4 volDemo = new VolatileDemo4();
		for(int i = 0 ; i < 500 ; i++){
/*			new Thread(new Runnable() {

				@Override
				public void run() {
					volDemo.increase();
				}
			}).start();*/
			//lambda表达式
			new Thread(()->volDemo.increase()).start();
		}

		//如果还有子线程在运行，主线程就让出CPU资源，
		//直到所有的子线程都运行完了，主线程再继续往下执行
		while(Thread.activeCount() > 1){
			Thread.yield();
		}

		System.out.println("number : " + volDemo.getNumber());
	}

}
